<template>

	<gui-page :customHeader='true'>
		<template v-slot:gBody>
			<Head :headBack="head_back" :showPopup="showPopup"  :greeting="greeting"
				:weather="weather"></Head>

			<scroll-view scroll-y="true" @scroll="scroll" @scrolltoupper="scrolltoupper" style="padding-top: 99rpx;"
				:style="{'margin-top':head_height}">
				<aoEditer v-if="pageConfig" ref="page1" :page="pageConfig" class="app" @event="aoedit_event">
				</aoEditer>
			</scroll-view>
		</template>
	</gui-page>
</template>
<script>
	import cdtDraggrableSort from "@/components/cdt-draggrable-sort/cdt-draggrable-sort.vue"
	import aoEditer from '@/components/common/aoEditer.vue'
	import Head from '@/components/index/Head.vue';
	import sign from "@/Grace6/js/sign.js";
	import {
		nextTick
	} from "vue";
	export default {
		components: {
			aoEditer,
			Head
		},

		data() {
			return {
				user: uni.getStorageSync("userInfo"),
				greeting: '',
				head_height: "-100rpx",
				isEdit: false,
				navList: [],
				pageConfig: uni.getStorageSync("pages_首页"),
				componentlist: [],
				head_back: "",
				showPopup: false,
				newslist: [],
				swiperItems: [],
				isback: false,
				myList: [],
				showTc: false,
				navIndex: 0,
				allList: [],
				debug: false,
				unread: 0,
				is_push: false,
				weather: {
					now: {
						text: ''
					}
				},
				opt: null,
				push_id: null,
			}
		},
		// beforeCreate() {

		// },
		// onLoad(opt) {


		// },
		mounted() {
			// 监听返回首页
			// uni.$on('get_unread', this.get_unread);
			// #ifdef APP-PLUS
			this.backButtonListener = this.get_unread.bind(this);
			plus.key.addEventListener('backbutton', this.backButtonListener);
			// #endif
		},
		created() {
			let self = this;
			this.update_page() //更新页面

			this.get_Indexdata(); //获取首页数据（新闻）
			// this.setGreeting();

			setTimeout(function() {
				self.getWeather(); //获取天气
				self.get_unread(); //获取未读
			}, 1000);

			this.os = uni.getSystemInfoSync().osName;
			if (uni.getStorageSync("userName") && uni.getStorageSync("password")) {
				let self = this
				uni.getPushClientId({
					success(res) {
						self.push_id = res.cid;
						console.log("push_id", self.push_id);
					}
				})

				// setTimeout(() => {
				// 	self.list_login()
				// }, 1000)

				// console.log('往这走了');

			}


			console.log("onLoad.pageConfig", this.pageConfig);

			// if (!opt.hasOwnProperty("back")) {
			// 	this.isback = false;
			// } else {
			// 	this.isback = true;
			// }
			// if (opt.hasOwnProperty("d")) {
			// 	this.debug = true;
			// 	console.log("load.debug");
			// 	this.update_page();
			// }
			// 天气
		},
		// onShow() {

		// },
		onPageScroll(e) {

			if (e.scrollTop > 10) {
				this.head_back = "background-color:white";
			} else {
				this.head_back = "";
			}
		},

		methods: {
			// list_login() {
			// 	let self = this
      //
			// 	console.log('self.push_id: ', self.push_id);
      //
			// 	let data = {
			// 		userName: uni.getStorageSync("userName"),
			// 		password: self.$lg.base64encode(uni.getStorageSync("ld").p),
			// 	}
			// 	// let data={};
			// 	// #ifdef APP-PLUS
			// 	data["devicesId"] = self.push_id;
			// 	// #endif
			// 	data["ttsxAuthSign"] = sign.sign(data).toString();
			// 	console.log("login.data", data);
      //
      //
      //
			// 	// #ifdef H5
			// 	console.log('执行了H5')
			// 	// url = "/test/APP/app/login";
			// 	// #endif
			// 	if (self.push_id) {
			// 		data["push_id"] = self.push_id;
			// 	}
			// 	data["os"] = self.os;
      //
			// 	console.log('数据datadatadata：', data);
			// 	self.$boya.NPost("/app/login", data, function(res) {
			// 		console.log("登录成功-->res", res);
			// 		// self.login_ok(res);
			// 	}, function(err) {
			// 		console.log("登录失败-->err", err);
			// 		if (err) {
			// 			if (err.msg.indexOf("参数校验失败") == -1) {
			// 				uni.showToast({
			// 					icon: "none",
			// 					title: err.msg
			// 				});
			// 			}
			// 		} else {
			// 			self.$boya.msg("自动登录失败!");
			// 			uni.reLaunch({
			// 				url: "/pages/login/login?logout=1"
			// 			})
			// 		}
			// 	}, {
			// 		showError: false
			// 	})
			// },
			// login_ok(res) {
			// 	console.log("login_ok: ", res);
			// 	uni.setStorageSync("ttsxAuthToken", res.data.ttsxAuthToken);
			// 	uni.setStorageSync("userInfo", res.data.user);
			// 	uni.setStorageSync("uuid", res.data.uuid);
			// 	console.log("uuid", res.data.uuid);
			// 	uni.setStorageSync("member", res.data.member);
			// 	uni.setStorageSync("platformMall", "c69a70c5-de6f-44fa-a333-88c5a5b3ff77")
			// },
			// 天气
			getWeather() {
				let self = this
				let city = null
				console.log(self.user);
				if(self.user=='' || self.user==null || self.user==undefined) return;
				if (self.user.orga.name.includes('广钢')) {
					city = '防城港'
				} else if (self.user.orga.name.includes('中金')) {
					city = '玉林'
				} else {
					city = '柳州'
				}
				let data = {
					city: city
				}

				this.$boya.NGet('/app/weather', data, function(res) {
					// console.log('天气-------1: ', res.data[0]);
					self.weather = res.data[0]
					console.log('天气-------2: ', self.weather);
				}, null, {
					showError: false
				})
			},

			setGreeting() {
				const now = new Date();
				const hour = now.getHours();

				if (hour >= 18 || hour < 6) {
					this.greeting = "晚上好";
				} else if (hour >= 6 && hour < 12) {
					this.greeting = "早上好";
				} else if (hour >= 12 && hour < 14) {
					this.greeting = "中午好";
				} else if (hour >= 14 && hour < 18) {
					this.greeting = "下午好";
				}
			},
			my_notice() {
				this.$boya.NGet("/app/msg_info/unread", {
					lock_state: 0
				}, (res) => {
					console.log("my_notice", res);
					if (res.data.length > 0) {
						// #ifdef APP-PLUS
						plus.push.createMessage("您有" + res.data.length + "条信息未读", {}, {
							cover: true,
							title: '消息提醒',
							sound: 'system',

						});
						// #endif
						uni.showModal({
							title: "提示",
							content: "您有" + res.data.length + "条消息未读",
							confirmText: "查看",
							cancelText: "关闭",
							success(e) {
								console.log(e);
								if (e.confirm) {
									uni.navigateTo({
										url: "/pages/home/message/message?type=1"
									})
								}
							}
						})
					}
				}, null, {
					showLoading: false
				});
			},

			get_unread() {
				// console.log('获取消息提示');
				let self = this;
				// #ifdef APP-PLUS
				this.$boya.NGet("/app/msg_info/unread", {}, (res) => {
					let msgcount = uni.getStorageSync("msgCount");
					if (msgcount != res.data) {
						msgcount = res.data
						console.log("#####get_unread->res", res.data)
						self.unread = res.data

						if (res.data > 0) {
							if (self.is_push == false) {
								self.is_push = true;
								plus.push.createMessage("您有" + res.data + "条信息未读", {}, {
									cover: true,
									title: '消息提醒',
									sound: 'system',

								});
							}
						}
					}
					let nav1 = self.$refs.page1.get_ref("nav1");
					nav1[0].badge(3, msgcount);
					self.unread = msgcount
					plus.runtime.setBadgeNumber(msgcount);
					console.log(self.unread);
				}, null, {
					showLoading: false
				})
				// #endif
			},
			aoedit_event(e) {
				console.log("index.aoedit_event", e);
				switch (e.type) {
					case "storenotecard":
						this.storenotecard_event(e.event)
						break;
				}
			},
			storenotecard_event(e) {
				if (e.type == "category_change") {
					this.get_news(e.value);
				}
			},



			navchange(index) {
				this.navIndex = index;
				this.newslist = [];
				this.get_news(this.navList[index].id);
			},

			get_news(id) {
				let self = this;
				let parm = null;
				if (id) {
					parm = {
						"category_id": id
					};
				}
				this.$boya.NGet("/app/news", parm, function(res) {
					// console.log(res);
					self.news(res.data.data, parm);
				});
			},
			news(res, parm = null) {

				let list = [];
				if (res) {
					for(let key in res){
						let item=res[key];
						let ditem = {
							src: this.$uimg + item.fid,
							text: item.title,
							linktype: 10,
							reads: item.look_num,
							likes: item.is_relay,
							http: {
								externalLink: "#/pages/news/newsDetail?id=" + item.id
							}
						};
						list.push(ditem);
					}
					this.newslist = list;

					this.$refs.page1.setData("articleList", this.newslist);
					if (parm) {
						if (parm.hasOwnProperty("category_id")) {
							this.$refs.page1.setData("articleList", parm.category_id, category_id);
						}
					}
					//this.$refs.page1.update_ref("articleList");
				}
			},


			update_page() {
				let self = this;

				this.$comm.get_appPages(function(res) {
					// console.log("update_page", res);
					if (res.ver != self.pageConfig.ver) {
						self.pageConfig = res;
						// uni.setStorageSync("pages_首页", res);
						try {
							self.$refs.page1.setPageConfig(res);
							console.log("update_page", "更新");
						} catch {
							this.nextTick(() => {
								self.$refs.page1.setPageConfig(res);
							})

						}

						self.set_indexData();
						if (self.debug) {

							uni.showToast({
								title: "更新完毕",
								icon: "none"
							})
						}
					}


				}, false, "首页");
			},
			init_pages(fnc) {
				let d = uni.getStorageSync("pages_首页");
				// console.log("pages_首页", d);
				this.get_Indexdata();
			},
			get_Indexdata() {
				let self = this;
				this.$boya.NGet("/app/index", null, (res) => {
					// console.log("index", res);
					uni.setStorageSync("index_data", res.data);

					self.set_indexData(res.data);
				}, null, {
					showLoading: false
				})
			},
			set_indexData(data = null) {
				if (data == null) {
					data = uni.getStorageSync("index_data");
				}
				// console.log("set_indexData", data);
				this.$nextTick(function() {
					this.newslist = [];
					this.category_news(data.category);
					this.news(data.news);
					this.swiper(data.swiper);
					this.notice(data.notice);
					this.my_notice();
					// this.sleep_data();

				})
			},
			scrolltoupper(e) {
				
				this.head_back = "";
			},
			scroll(e) {
				// console.log("scroll",e);
				if (e.detail.deltaY < -0.1) {
					this.head_back = "background-color:white";
					// console.log("scroll",e);
				}
			},
			showPopup1() {
				this.showPopup = true
				// console.log('--12-1-')
			},
			// sleep_data() {

			// },
			category_news(res) {
				// console.log("category_news",res)
				let arr = [];

				this.$refs.page1.setData("articleList", res, "categorys");

				// console.log("category_news", this.navList, this.allList);
			},
			notice(res) {
				let arr = [];
				for (let key in res) {
					// { title: "lesscode.work - 精品 IT 课程中心", url: "../index/index", opentype: "switchTab"}
					let item = res[key];
					arr.push({
						title: item.title,
						url: '/pages/home/notice/index?id=' + item.id,
						opentype: "navigate"
					})
				}
				this.$nextTick(() => {
					let gg = this.$refs.page1.get_ref("gg");
					if (gg) {
						gg.items = arr;
					}
				})

			},

			swiper(res) {
				
				this.swiperItems = [];
				this.swiperData = res;
				let linktype = '10';
				for (let key in res) {
					let item = res[key];
					let uimg = JSON.parse(item.index_url_app);
					let url = "#/pages/news/newsDetail?id=" + item.link;
					

					
					this.swiperItems.push({
						src: this.$uimg + uimg.id,
						text: item.title,
						linktype: linktype,
						http: {
							externalLink: url
						}
					})

				}
				
				this.$refs.page1.setData("lbt", this.swiperItems);
			},


			page_style() {
				let _style = this.page.templateJson.Style;
				if (this.page.templateJson.bgColor != "") {
					_style.backgroundColor = this.page.templateJson.bgColor
				}
				if (this.page.templateJson.bgImg != "") {
					_style.backgroundImage = "url(" + this.page.templateJson.bgImg + ")"
				}
				return _style;
			},
			
		}
	}
</script>
<style>
	.app {
		position: relative;
		height: 100vh;
		/* overflow-y: scroll; */
	}

	.head {
		height: calc(var(--status-bar-height)+70rpx);
		z-index: 99999;

		width: 100%;
		position: fixed;
		top: var(--window-top);
		padding-top: var(--status-bar-height);
		padding-left: 20rpx;
		padding-right: 140rpx;
		padding-bottom: 10rpx;
		align-items: center;
	}
</style>